package com.qms.repast.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.orhanobut.logger.Logger;
import com.qms.repast.R;
import com.qms.repast.aspectj.login.CheckLogin;
import com.qms.repast.commons.AppLocation;
import com.qms.repast.commons.Constants;
import com.qms.repast.commons.GlideApp;
import com.qms.repast.entity.MessageEvent;
import com.qms.repast.entity.resbean.LocationBean;
import com.qms.repast.entity.resbean.UserInfo;
import com.qms.repast.ui.adapter.TabFragmentPagerAdapter;
import com.qms.repast.ui.base.BaseFragmentActivity;
import com.qms.repast.ui.fragment.OrderFragment;
import com.qms.repast.ui.fragment.ReserveFragment;
import com.qms.repast.ui.fragment.ServingFragment;
import com.qms.repast.utils.AppUtils;
import com.qms.repast.utils.SpUtils;
import com.qms.repast.utils.UserSpUtils;
import com.qms.repast.weidgets.ScaleTransitionPagerTitleView;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.UIUtil;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.SimplePagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.badge.BadgePagerTitleView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator.MODE_WRAP_CONTENT;

/**
 * @author 泅渡者
 * @date 2018/9/3 0031
 * @describe: 主界面
 */
public class MainActivity extends BaseFragmentActivity {

	/**
	 * 栏目名称
	 */
	private static final String[] CHANNELS = new String[]{"订桌", "点餐", "上菜"};
	public static final String MESSAGE_RECEIVED_ACTION = "com.qms.repast.MESSAGE_RECEIVED_ACTION";
	public static final String KEY_MESSAGE = "message";
	public static final String KEY_EXTRAS = "extras";

	@BindView(R.id.magic_indicator)
	MagicIndicator magicIndicator;
	@BindView(R.id.view_pager)
	ViewPager viewPager;
	@BindView(R.id.right_drawer_layout)
	RelativeLayout rightDrawerLayout;
	@BindView(R.id.drawer_layout)
	DrawerLayout drawerLayout;
	@BindView(R.id.iv_search)
	ImageView ivSearch;
	@BindView(R.id.iv_user)
	ImageView ivUser;
	@BindView(R.id.rl_userInfo)
	RelativeLayout rlUserInfo;
	@BindView(R.id.rl_toLogin)
	RelativeLayout rl_toLogin;
	@BindView(R.id.ll_location)
	RelativeLayout llLocation;
	@BindView(R.id.iv_setting)
	ImageView ivSetting;
	@BindView(R.id.iv_location_placeholder)
	ImageView ivLocationPlaceholder;
	@BindView(R.id.tv_location)
	TextView tvLocation;
	@BindView(R.id.tv_telPhone)
	TextView tvTelPhone;
	@BindView(R.id.tv_userName)
	TextView tvUserName;
	@BindView(R.id.iv_arrow)
	ImageView ivArrow;
	@BindView(R.id.iv_headpic)
	ImageView ivHeadpic;
	@BindView(R.id.ll_info)
	LinearLayout llInfo;
	@BindView(R.id.ll_exit)
	LinearLayout llExit;
	@BindView(R.id.iv_message)
	ImageView ivMessage;

	private List<String> mDataList = Arrays.asList(CHANNELS);
	private List<Fragment> list;
	private TabFragmentPagerAdapter adapter;
	private ActionBarDrawerToggle drawerbar;

	public static boolean isForeground = false;

	@Override
	protected int initLayout () {
		return R.layout.activity_main;
	}

	@Override
	protected void handleIntent (Intent intent) {

	}

	@Override
	protected void initView () {
		EventBus.getDefault().register(this);
		AppLocation.startLocation();
		list = new ArrayList<>();
		list.add(new ReserveFragment());
		list.add(new OrderFragment());
		list.add(new ServingFragment());
		adapter = new TabFragmentPagerAdapter(getSupportFragmentManager(), list);

		viewPager.setAdapter(adapter);
		initMagicIndicator();
		viewPager.setCurrentItem(0);


		drawerLayout.setScrimColor(ContextCompat.getColor(this, R.color.color_Black_transparency));
		drawerbar = new ActionBarDrawerToggle(this, drawerLayout, R.mipmap.ic_launcher, R.string.drawer_open, R.string.drawer_close) {
			@Override
			public void onDrawerOpened (View drawerView) {
				super.onDrawerOpened(drawerView);
			}

			@Override
			public void onDrawerClosed (View drawerView) {
				super.onDrawerClosed(drawerView);
			}
		};
		drawerLayout.setDrawerListener(drawerbar);

		if (UserSpUtils.isLogin(AppUtils.getContext())) {
			UserInfo userInfo = new Gson().fromJson(UserSpUtils.getUserInfo(AppUtils.getContext()), UserInfo.class);
			updateInfo(userInfo);
		}
	}


	@Subscribe
	public void onEventMainThread (MessageEvent messageEvent) {
		switch (messageEvent.getCode()) {
			//城市切换
			case 1011:
				LocationBean locationBean = (LocationBean) messageEvent.getMessage();
				if (null != locationBean) {
					if (!TextUtils.isEmpty(locationBean.getCity())) {
						SpUtils.setParam(AppUtils.getContext(), Constants.CITY, locationBean.getCity());
					}
					if (!TextUtils.isEmpty(locationBean.getCityId())) {
						SpUtils.setParam(AppUtils.getContext(), Constants.CITYID, locationBean.getCityId());
					}
					if (null != locationBean.getLatitude() && 0 != locationBean.getLatitude()) {
						SpUtils.setParam(AppUtils.getContext(), Constants.LAT, locationBean.getLatitude());
					}
					if (null != locationBean.getLongitude() && 0 != locationBean.getLongitude()) {
						SpUtils.setParam(AppUtils.getContext(), Constants.LNG, locationBean.getLongitude());
					}
					Logger.d(locationBean.toString());
				}
				tvLocation.setText((String) SpUtils.getParam(AppUtils.getContext(), Constants.CITY, ""));
				break;
			//刷新用户信息
			case 1012:
				UserInfo userInfo = (UserInfo) messageEvent.getMessage();
				updateInfo(userInfo);
				break;
			default:
				break;
		}
	}

	private void updateInfo (UserInfo userInfo) {
		RequestOptions requestOptions = RequestOptions.circleCropTransform();
		if (null == userInfo) {
			rlUserInfo.setVisibility(View.GONE);
			rl_toLogin.setVisibility(View.VISIBLE);
			tvUserName.setText("———");
			tvTelPhone.setText("———————");
			GlideApp.with(AppUtils.getContext()).load("").apply(requestOptions).placeholder(R.drawable.ex_head).into(ivHeadpic);
		} else {
			rlUserInfo.setVisibility(View.VISIBLE);
			rl_toLogin.setVisibility(View.GONE);
			String nickName = userInfo.getBody().getUserNameLogin().getNickName();
			String phoneNumber = userInfo.getBody().getUserNameLogin().getPhoneNumber();
			String picUrl = userInfo.getBody().getUserNameLogin().getPicUrl();
			if (TextUtils.isEmpty(nickName)) {
				tvUserName.setText("———");
			} else {
				tvUserName.setText(nickName);
			}
			if (TextUtils.isEmpty(phoneNumber)) {
				tvTelPhone.setText("———————");
			} else {
				tvTelPhone.setText(phoneNumber);
			}
			GlideApp.with(AppUtils.getContext()).load(picUrl).apply(requestOptions).into(ivHeadpic);
		}
	}

	@Override
	protected void onResume () {
		isForeground = true;
		super.onResume();
	}

	@Override
	protected void onPause () {
		isForeground = false;
		super.onPause();
	}

	@Override
	protected void onDestroy () {
		super.onDestroy();
		if (EventBus.getDefault().isRegistered(this)) {
			EventBus.getDefault().unregister(this);
		}
	}

	/**
	 * 初始化标签
	 */
	private void initMagicIndicator () {
		magicIndicator.setBackgroundColor(Color.WHITE);
		CommonNavigator commonNavigator = new CommonNavigator(this);
		commonNavigator.setAdjustMode(true);
		commonNavigator.setAdapter(new CommonNavigatorAdapter() {
			@Override
			public int getCount () {
				return mDataList == null ? 0 : mDataList.size();
			}

			@Override
			public IPagerTitleView getTitleView (Context context, final int index) {
				BadgePagerTitleView badgePagerTitleView = new BadgePagerTitleView(context);

				SimplePagerTitleView simplePagerTitleView = new ScaleTransitionPagerTitleView(context);
				simplePagerTitleView.setText(mDataList.get(index));
				simplePagerTitleView.setTextSize(18);
				simplePagerTitleView.setNormalColor(Color.parseColor("#616161"));
				simplePagerTitleView.setSelectedColor(Color.parseColor("#f57c00"));
				simplePagerTitleView.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick (View v) {
						viewPager.setCurrentItem(index);
					}
				});
				badgePagerTitleView.setInnerPagerTitleView(simplePagerTitleView);
				badgePagerTitleView.setAutoCancelBadge(true);

				return badgePagerTitleView;
			}

			@Override
			public IPagerIndicator getIndicator (Context context) {
				LinePagerIndicator indicator = new LinePagerIndicator(context);
				indicator.setStartInterpolator(new AccelerateInterpolator());
				indicator.setEndInterpolator(new DecelerateInterpolator(1.6f));
				indicator.setLineHeight(UIUtil.dip2px(context, 1));
				indicator.setColors(Color.parseColor("#f57c00"));
				indicator.setMode(MODE_WRAP_CONTENT);
				return indicator;
			}

			@Override
			public float getTitleWeight (Context context, int index) {
				if (index == 0) {
					return 1.0f;
				} else if (index == 1) {
					return 1.0f;
				} else {
					return 1.0f;
				}
			}

		});
		magicIndicator.setNavigator(commonNavigator);
		ViewPagerHelper.bind(magicIndicator, viewPager);
	}

	@OnClick({R.id.iv_search, R.id.iv_user, R.id.ll_location, R.id.iv_setting, R.id.ll_exit})
	public void onViewClicked (View view) {
		switch (view.getId()) {
			case R.id.iv_search:
				startActivity(new Intent(MainActivity.this, SearchActivity.class));
				break;
			case R.id.iv_user:
				openRightLayout();
				break;
			case R.id.ll_location:
				startActivity(new Intent(this, CityListActivity.class));
				break;
			case R.id.iv_setting:
				startActivity(new Intent(this, SettingActivity.class));
				break;
			case R.id.ll_exit:
				SpUtils.setParam(AppUtils.getContext(), Constants.SESSION, "");
				UserSpUtils.clearUserInfo(AppUtils.getContext());
				updateInfo(null);
				break;
			default:
				break;
		}
	}

	/**
	 * 右边抽屉菜单
	 */
	public void openRightLayout () {

		if (drawerLayout.isDrawerOpen(rightDrawerLayout)) {
			drawerLayout.closeDrawer(rightDrawerLayout);
		} else {
			drawerLayout.openDrawer(rightDrawerLayout);
		}

	}

	@CheckLogin
	@OnClick(R.id.rl_userInfo)
	public void onViewClicked () {
		startActivity(new Intent(this, UserActivity.class));
	}

	@CheckLogin
	@OnClick(R.id.rl_toLogin)
	public void onToLoginClicked () {
		startActivity(new Intent(this, UserActivity.class));
	}
}
